package com.hsy.leancloudchat.chat

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cn.leancloud.im.v2.LCIMMessage
import com.hsy.leancloudchat.LeanCloudHelper
import com.hsy.leancloudchat.databinding.ItemChatMyselfBinding
import com.hsy.leancloudchat.databinding.ItemChatOthersBinding

class ChatAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var messageList = mutableListOf<LCIMMessage>()
        @SuppressLint("NotifyDataSetChanged")
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    override fun getItemViewType(position: Int): Int {
        return if (messageList[position].from != LeanCloudHelper.mCurrentClientLiveData.value?.clientId) {
            0 // 不是自己的消息
        } else {
            1 // 是自己的消息
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            0 -> ChatOthersViewHolder(ItemChatOthersBinding.inflate(layoutInflater))
            1 -> ChatMyselfViewHolder(ItemChatMyselfBinding.inflate(layoutInflater))
            else -> throw IllegalStateException("ChatAdapter: onCreateViewHolder -> 没这个类型")
        }
    }

    override fun getItemCount(): Int {
        return messageList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is ChatOthersViewHolder -> holder.bind(position)
            is ChatMyselfViewHolder -> holder.bind(position)
        }
    }

    inner class ChatOthersViewHolder(private val binding: ItemChatOthersBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            val message = messageList[position]
            binding.apply {
                tvMessage.text =
                    LeanCloudHelper.getInstance().parseMessageContentForText(message.content)
                tvTime.text = LeanCloudHelper.getInstance().parseTimeStamp(message.timestamp)
            }
        }
    }

    inner class ChatMyselfViewHolder(private val binding: ItemChatMyselfBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            val message = messageList[position]
            binding.apply {
                tvMessage.text =
                    LeanCloudHelper.getInstance().parseMessageContentForText(message.content)
                tvTime.text = LeanCloudHelper.getInstance().parseTimeStamp(message.timestamp)
            }
        }
    }
}